home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 26 / Cream of the Crop 26.iso / os2 / timidsrc.zip / readmidi.c < prev    next >
C/C++ Source or Header  |  1996-05-20  |  16KB  |  629 lines

  1. /*
  2.  
  3.     TiMidity -- Experimental MIDI to WAVE converter
  4.     Copyright (C) 1995 Tuukka Toivonen <toivonen@clinet.fi>
  5.  
  6.     This program is free software; you can redistribute it and/or modify
  7.     it under the terms of the GNU General Public License as published by
  8.     the Free Software Foundation; either version 2 of the License, or
  9.     (at your option) any later version.
  10.  
  11.     This program is distributed in the hope that it will be useful,
  12.     but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.     GNU General Public License for more details.
  15.  
  16.     You should have received a copy of the GNU General Public License
  17.     along with this program; if not, write to the Free Software
  18.     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  19.  
  20. */
  21.  
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <errno.h>
  25.  
  26. #if defined(SOLARIS) | defined(__WIN32__)
  27. # include <string.h>
  28. #else
  29. #include <strings.h>
  30. #endif
  31.  
  32. #ifndef __WIN32__
  33. #include <unistd.h>
  34. #endif
  35.  
  36. #include "config.h"
  37. #include "common.h"
  38. #include "instrum.h"
  39. #include "playmidi.h"
  40. #include "readmidi.h"
  41. #include "output.h"
  42. #include "controls.h"
  43.  
  44. int32 quietchannels=0;
  45.  
  46. /* to avoid some unnecessary parameter passing */
  47. static MidiEventList *evlist;
  48. static int32 event_count;
  49. static FILE *fp;
  50. static int32 at;
  51.  
  52. /* These would both fit into 32 bits, but they are often added in
  53.    large multiples, so it's simpler to have two roomy ints */
  54. static int32 sample_increment, sample_correction; /*samples per MIDI delta-t*/
  55.  
  56. /* Computes how many (fractional) samples one MIDI delta-time unit contains */
  57. static void compute_sample_increment(int32 tempo, int32 divisions)
  58. {
  59.   double a;
  60.   a = (double) (tempo) * (double) (play_mode->rate) * (65536.0/1000000.0) /
  61.     (double)(divisions);
  62.  
  63.   sample_correction = (int32)(a) & 0xFFFF;
  64.   sample_increment = (int32)(a) >> 16;
  65.  
  66.   ctl->cmsg(CMSG_INFO, VERB_DEBUG, "Samples per delta-t: %d (correction %d)",
  67.        sample_increment, sample_correction);
  68. }
  69.  
  70. /* Read variable-length number (7 bits per byte, MSB first) */
  71. static int32 getvl(void)
  72. {
  73.   int32 l=0;
  74.   uint8 c;
  75.   for (;;)
  76.     {
  77.       fread(&c,1,1,fp);
  78.       l += (c & 0x7f);
  79.       if (!(c & 0x80)) return l;
  80.       l<<=7;
  81.     }
  82. }
  83.  
  84. /* Print a string from the file, followed by a newline. Any non-ASCII
  85.    or unprintable characters will be converted to periods. */
  86. static int dumpstring(int32 len, char *label)
  87. {
  88.   signed char *s=safe_malloc(len+1);
  89.   if (len != fread(s, 1, len, fp))
  90.     {
  91.       free(s);
  92.       return -1;
  93.     }
  94.   s[len]='\0';
  95.   while (len--)
  96.     {
  97.       if (s[len]<32)
  98.     s[len]='.';
  99.     }
  100.   ctl->cmsg(CMSG_TEXT, VERB_VERBOSE, "%s%s", label, s);
  101.   free(s);
  102.   return 0;
  103. }
  104.  
  105. #define MIDIEVENT(at,t,ch,pa,pb) \
  106.   new=safe_malloc(sizeof(MidiEventList)); \
  107.   new->event.time=at; new->event.type=t; new->event.channel=ch; \
  108.   new->event.a=pa; new->event.b=pb; new->next=0;\
  109.   return new;
  110.  
  111. #define MAGIC_EOT ((MidiEventList *)(-1))
  112.  
  113. /* Read a MIDI event, returning a freshly allocated element that can
  114.    be linked to the event list */
  115. static MidiEventList *read_midi_event(void)
  116. {
  117.   static uint8 laststatus, lastchan;
  118.   static uint8 nrpn=0, rpn_msb[16], rpn_lsb[16]; /* one per channel */
  119.   uint8 me, type, a,b,c;
  120.   int32 len;
  121.   MidiEventList *new;
  122.  
  123.   for (;;)
  124.     {
  125.       at+=getvl();
  126.       if (fread(&me,1,1,fp)!=1)
  127.     {
  128.       ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: read_midi_event: %s", 
  129.            current_filename, sys_errlist[errno]);
  130.       return 0;
  131.     }
  132.       
  133.       if(me==0xF0 || me == 0xF7) /* SysEx event */
  134.     {
  135.       len=getvl();
  136.       skip(fp, len);
  137.     }
  138.       else if(me==0xFF) /* Meta event */
  139.     {
  140.       fread(&type,1,1,fp);
  141.       len=getvl();
  142.       if (type>0 && type<16)
  143.         {
  144.           static char *label[]={
  145.         "Text event: ", "Text: ", "Copyright: ", "Track name: ",
  146.         "Instrument: ", "Lyric: ", "Marker: ", "Cue point: "};
  147.           dumpstring(len, label[(type>7) ? 0 : type]);
  148.         }
  149.       else
  150.         switch(type)
  151.           {
  152.           case 0x2F: /* End of Track */
  153.         return MAGIC_EOT;
  154.  
  155.           case 0x51: /* Tempo */
  156.         fread(&a,1,1,fp); fread(&b,1,1,fp); fread(&c,1,1,fp);
  157.         MIDIEVENT(at, ME_TEMPO, c, a, b);
  158.         
  159.           default:
  160.         ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
  161.              "(Meta event type 0x%02x, length %ld)", type, len);
  162.         skip(fp, len);
  163.         break;
  164.           }
  165.     }
  166.       else
  167.     {
  168.       a=me;
  169.       if (a & 0x80) /* status byte */
  170.         {
  171.           lastchan=a & 0x0F;
  172.           laststatus=(a>>4) & 0x07;
  173.           fread(&a, 1,1, fp);
  174.           a &= 0x7F;
  175.         }
  176.       switch(laststatus)
  177.         {
  178.         case 0: /* Note off */
  179.           fread(&b, 1,1, fp);
  180.           b &= 0x7F;
  181.           MIDIEVENT(at, ME_NOTEOFF, lastchan, a,b);
  182.  
  183.         case 1: /* Note on */
  184.           fread(&b, 1,1, fp);
  185.           b &= 0x7F;
  186.           MIDIEVENT(at, ME_NOTEON, lastchan, a,b);
  187.  
  188.         case 2: /* Key Pressure */
  189.           fread(&b, 1,1, fp);
  190.           b &= 0x7F;
  191.           MIDIEVENT(at, ME_KEYPRESSURE, lastchan, a, b);
  192.  
  193.         case 3: /* Control change */
  194.           fread(&b, 1,1, fp);
  195.           b &= 0x7F;
  196.           {
  197.         int control=255;
  198.         switch(a)
  199.           {
  200.           case 7: control=ME_MAINVOLUME; break;
  201.           case 10: control=ME_PAN; break;
  202.           case 11: control=ME_EXPRESSION; break;
  203.           case 64: control=ME_SUSTAIN; break;
  204.           case 120: control=ME_ALL_SOUNDS_OFF; break;
  205.           case 121: control=ME_RESET_CONTROLLERS; break;
  206.           case 123: control=ME_ALL_NOTES_OFF; break;
  207.  
  208.             /* These should be the SCC-1 tone bank switch
  209.                commands. I don't know why there are two, or
  210.                why the latter only allows switching to bank 0.
  211.                Also, some MIDI files use 0 as some sort of
  212.                continuous controller. This will cause lots of
  213.                warnings about undefined tone banks. */
  214.           case 0: control=ME_TONE_BANK; break;
  215.           case 32: 
  216.             if (b!=0)
  217.               ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
  218.                 "(Strange: tone bank change 0x20%02x)", b);
  219.             else
  220.               control=ME_TONE_BANK;
  221.             break;
  222.  
  223.           case 100: nrpn=0; rpn_msb[lastchan]=b; break;
  224.           case 101: nrpn=0; rpn_lsb[lastchan]=b; break;
  225.           case 99: nrpn=1; rpn_msb[lastchan]=b; break;
  226.           case 98: nrpn=1; rpn_lsb[lastchan]=b; break;
  227.             
  228.           case 6:
  229.             if (nrpn)
  230.               {
  231.             ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
  232.                   "(Data entry (MSB) for NRPN %02x,%02x: %ld)",
  233.                   rpn_msb[lastchan], rpn_lsb[lastchan],
  234.                   b);
  235.             break;
  236.               }
  237.             
  238.             switch((rpn_msb[lastchan]<<8) | rpn_lsb[lastchan])
  239.               {
  240.               case 0x0000: /* Pitch bend sensitivity */
  241.             control=ME_PITCH_SENS;
  242.             break;
  243.  
  244.               case 0x7F7F: /* RPN reset */
  245.             /* reset pitch bend sensitivity to 2 */
  246.             MIDIEVENT(at, ME_PITCH_SENS, lastchan, 2, 0);
  247.  
  248.               default:
  249.             ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
  250.                   "(Data entry (MSB) for RPN %02x,%02x: %ld)",
  251.                   rpn_msb[lastchan], rpn_lsb[lastchan],
  252.                   b);
  253.             break;
  254.               }
  255.             break;
  256.             
  257.           default:
  258.             ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
  259.                   "(Control %d: %d)", a, b);
  260.             break;
  261.           }
  262.         if (control != 255)
  263.           { 
  264.             MIDIEVENT(at, control, lastchan, b, 0); 
  265.           }
  266.           }
  267.           break;
  268.  
  269.         case 4: /* Program change */
  270.           a &= 0x7f;
  271.           MIDIEVENT(at, ME_PROGRAM, lastchan, a, 0);
  272.  
  273.         case 5: /* Channel pressure - NOT IMPLEMENTED */
  274.           break;
  275.  
  276.         case 6: /* Pitch wheel */
  277.           fread(&b, 1,1, fp);
  278.           b &= 0x7F;
  279.           MIDIEVENT(at, ME_PITCHWHEEL, lastchan, a, b);
  280.  
  281.         default: 
  282.           ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
  283.            "*** Can't happen: status 0x%02X, channel 0x%02X",
  284.            laststatus, lastchan);
  285.           break;
  286.         }
  287.     }
  288.     }
  289.   
  290.   return new;
  291. }
  292.  
  293. #undef MIDIEVENT
  294.  
  295. /* Read a midi track into the linked list, either merging with any previous
  296.    tracks or appending to them. */
  297. static int read_track(int append)
  298. {
  299.   MidiEventList *meep;
  300.   MidiEventList *next, *new;
  301.   int32 len;
  302.   char tmp[4];
  303.  
  304.   meep=evlist;
  305.   if (append && meep)
  306.     {
  307.       /* find the last event in the list */
  308.       for (; meep->next; meep=meep->next)
  309.     ;
  310.       at=meep->event.time;
  311.     }
  312.   else
  313.     at=0;
  314.  
  315.   /* Check the formalities */
  316.   
  317.   if ((fread(tmp,1,4,fp) != 4) || (fread(&len,4,1,fp) != 1))
  318.     {
  319.       ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
  320.        "%s: Can't read track header.", current_filename);
  321.       return -1;
  322.     }
  323.   len=BE_LONG(len);
  324.   if (memcmp(tmp, "MTrk", 4))
  325.     {
  326.       ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
  327.        "%s: Corrupt MIDI file.", current_filename);
  328.       return -2;
  329.     }
  330.  
  331.   for (;;)
  332.     {
  333.       if (!(new=read_midi_event())) /* Some kind of error  */
  334.     return -2;
  335.  
  336.       if (new==MAGIC_EOT) /* End-of-track Hack. */
  337.     {
  338.       return 0;
  339.     }
  340.  
  341.       next=meep->next;
  342.       while (next && (next->event.time < new->event.time))
  343.     {
  344.       meep=next;
  345.       next=meep->next;
  346.     }
  347.       
  348.       new->next=next;
  349.       meep->next=new;
  350.  
  351.       event_count++; /* Count the event. (About one?) */
  352.       meep=new;
  353.     }
  354. }
  355.  
  356. /* Free the linked event list from memory. */
  357. static void free_midi_list(void)
  358. {
  359.   MidiEventList *meep, *next;
  360.   if (!(meep=evlist)) return;
  361.   while (meep)
  362.     {
  363.       next=meep->next;
  364.       free(meep);
  365.       meep=next;
  366.     }
  367.   evlist=0;
  368. }
  369.  
  370. /* Allocate an array of MidiEvents and fill it from the linked list of
  371.    events, marking used instruments for loading. Convert event times to
  372.    samples: handle tempo changes. Strip unnecessary events from the list.
  373.    Free the linked list. */
  374. static MidiEvent *groom_list(int32 divisions,int32 *eventsp,int32 *samplesp)
  375. {
  376.   MidiEvent *groomed_list, *lp;
  377.   MidiEventList *meep;
  378.   int32 i, our_event_count, tempo, skip_this_event, new_value;
  379.   int32 sample_cum, samples_to_do, at, st, dt, counting_time;
  380.  
  381.   int current_bank[16], current_set[16], current_program[16]; 
  382.   /* Or should each bank have its own current program? */
  383.  
  384.   for (i=0; i<16; i++)
  385.     {
  386.       current_bank[i]=0;
  387.       current_set[i]=0;
  388.       current_program[i]=default_program;
  389.     }
  390.  
  391.   tempo=500000;
  392.   compute_sample_increment(tempo, divisions);
  393.  
  394.   /* This may allocate a bit more than we need */
  395.   groomed_list=lp=safe_malloc(sizeof(MidiEvent) * (event_count+1));
  396.   meep=evlist;
  397.  
  398.   our_event_count=0;
  399.   st=at=sample_cum=0;
  400.   counting_time=2; /* We strip any silence before the first NOTE ON. */
  401.  
  402.   for (i=0; i<event_count; i++)
  403.     {
  404.       skip_this_event=0;
  405.       ctl->cmsg(CMSG_INFO, VERB_DEBUG_SILLY,
  406.         "%6d: ch %2d: event %d (%d,%d)",
  407.         meep->event.time, meep->event.channel + 1,
  408.         meep->event.type, meep->event.a, meep->event.b);
  409.  
  410.       if (meep->event.type==ME_TEMPO)
  411.     {
  412.       tempo=
  413.         meep->event.channel + meep->event.b * 256 + meep->event.a * 65536;
  414.       compute_sample_increment(tempo, divisions);
  415.       skip_this_event=1;
  416.     }
  417.       else if ((quietchannels & (1<<meep->event.channel)))
  418.     skip_this_event=1;
  419.       else switch (meep->event.type)
  420.     {
  421.     case ME_PROGRAM:
  422.       if (ISDRUMCHANNEL(meep->event.channel))
  423.         {
  424.           if (drumset[meep->event.a]) /* Is this a defined drumset? */
  425.         new_value=meep->event.a;
  426.           else
  427.         {
  428.           ctl->cmsg(CMSG_WARNING, VERB_VERBOSE,
  429.                "Drum set %d is undefined", meep->event.a);
  430.           new_value=meep->event.a=0;
  431.         }
  432.           if (current_set[meep->event.channel] != new_value)
  433.         current_set[meep->event.channel]=new_value;
  434.           else 
  435.         skip_this_event=1;
  436.         }
  437.       else
  438.         {
  439.           new_value=meep->event.a;
  440.           if ((current_program[meep->event.channel] != SPECIAL_PROGRAM)
  441.           && (current_program[meep->event.channel] != new_value))
  442.         current_program[meep->event.channel] = new_value;
  443.           else
  444.         skip_this_event=1;
  445.         }
  446.       break;
  447.  
  448.     case ME_NOTEON:
  449.       if (counting_time)
  450.         counting_time=1;
  451.       if (ISDRUMCHANNEL(meep->event.channel))
  452.         {
  453.           /* Mark this instrument to be loaded */
  454.           if (!(drumset[current_set[meep->event.channel]]
  455.             ->tone[meep->event.a].instrument))
  456.         drumset[current_set[meep->event.channel]]
  457.           ->tone[meep->event.a].instrument=
  458.             MAGIC_LOAD_INSTRUMENT;
  459.         }
  460.       else
  461.         {
  462.           if (current_program[meep->event.channel]==SPECIAL_PROGRAM)
  463.         break;
  464.           /* Mark this instrument to be loaded */
  465.           if (!(tonebank[current_bank[meep->event.channel]]
  466.             ->tone[current_program[meep->event.channel]].instrument))
  467.         tonebank[current_bank[meep->event.channel]]
  468.           ->tone[current_program[meep->event.channel]].instrument=
  469.             MAGIC_LOAD_INSTRUMENT;
  470.         }
  471.       break;
  472.  
  473.     case ME_TONE_BANK:
  474.       if (ISDRUMCHANNEL(meep->event.channel))
  475.         {
  476.           skip_this_event=1;
  477.           break;
  478.         }
  479.       if (tonebank[meep->event.a]) /* Is this a defined tone bank? */
  480.         new_value=meep->event.a;
  481.       else 
  482.         {
  483.           ctl->cmsg(CMSG_WARNING, VERB_VERBOSE,
  484.            "Tone bank %d is undefined", meep->event.a);
  485.           new_value=meep->event.a=0;
  486.         }
  487.       if (current_bank[meep->event.channel]!=new_value)
  488.         current_bank[meep->event.channel]=new_value;
  489.       else
  490.         skip_this_event=1;
  491.       break;
  492.     }
  493.  
  494.       /* Recompute time in samples*/
  495.       if ((dt=meep->event.time - at) && !counting_time)
  496.     {
  497.       samples_to_do=sample_increment * dt;
  498.       sample_cum += sample_correction * dt;
  499.       if (sample_cum & 0xFFFF0000)
  500.         {
  501.           samples_to_do += ((sample_cum >> 16) & 0xFFFF);
  502.           sample_cum &= 0x0000FFFF;
  503.         }
  504.       st += samples_to_do;
  505.     }
  506.       else if (counting_time==1) counting_time=0;
  507.       if (!skip_this_event)
  508.     {
  509.       /* Add the event to the list */
  510.       *lp=meep->event;
  511.       lp->time=st;
  512.       lp++;
  513.       our_event_count++;
  514.     }
  515.       at=meep->event.time;
  516.       meep=meep->next;
  517.     }
  518.   /* Add an End-of-Track event */
  519.   lp->time=st;
  520.   lp->type=ME_EOT;
  521.   our_event_count++;
  522.   free_midi_list();
  523.   
  524.   *eventsp=our_event_count;
  525.   *samplesp=st;
  526.   return groomed_list;
  527. }
  528.  
  529. MidiEvent *read_midi_file(FILE *mfp, int32 *count, int32 *sp)
  530. {
  531.   int32 len, divisions;
  532.   int16 format, tracks, divisions_tmp;
  533.   int i;
  534.   char tmp[4];
  535.  
  536.   fp=mfp;
  537.   event_count=0;
  538.   at=0;
  539.   evlist=0;
  540.  
  541.   if ((fread(tmp,1,4,fp) != 4) || (fread(&len,4,1,fp) != 1))
  542.     {
  543.       if (ferror(fp))
  544.     {
  545.       ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: %s", current_filename, 
  546.            sys_errlist[errno]);
  547.     }
  548.       else
  549.     ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
  550.          "%s: Not a MIDI file!", current_filename);
  551.       return 0;
  552.     }
  553.   len=BE_LONG(len);
  554.   if (memcmp(tmp, "MThd", 4) || len < 6)
  555.     {
  556.       ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
  557.        "%s: Not a MIDI file!", current_filename);
  558.       return 0;
  559.     }
  560.  
  561.   fread(&format, 2, 1, fp);
  562.   fread(&tracks, 2, 1, fp);
  563.   fread(&divisions_tmp, 2, 1, fp);
  564.   format=BE_SHORT(format);
  565.   tracks=BE_SHORT(tracks);
  566.   divisions_tmp=BE_SHORT(divisions_tmp);
  567.  
  568.   if (divisions_tmp<0)
  569.     {
  570.       /* SMPTE time -- totally untested. Got a MIDI file that uses this? */
  571.       divisions=
  572.     (int32)(-(divisions_tmp/256)) * (int32)(divisions_tmp & 0xFF);
  573.     }
  574.   else divisions=(int32)(divisions_tmp);
  575.  
  576.   if (len > 6)
  577.     {
  578.       ctl->cmsg(CMSG_WARNING, VERB_NORMAL, 
  579.        "%s: MIDI file header size %ld bytes", 
  580.        current_filename, len);
  581.       skip(fp, len-6); /* skip the excess */
  582.     }
  583.   if (format<0 || format >2)
  584.     {
  585.       ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
  586.        "%s: Unknown MIDI file format %d", current_filename, format);
  587.       return 0;
  588.     }
  589.   ctl->cmsg(CMSG_INFO, VERB_VERBOSE, 
  590.        "Format: %d  Tracks: %d  Divisions: %d", format, tracks, divisions);
  591.  
  592.   /* Put a do-nothing event first in the list for easier processing */
  593.   evlist=safe_malloc(sizeof(MidiEventList));
  594.   evlist->event.time=0;
  595.   evlist->event.type=ME_NONE;
  596.   evlist->next=0;
  597.   event_count++;
  598.  
  599.   switch(format)
  600.     {
  601.     case 0:
  602.       if (read_track(0))
  603.     {
  604.       free_midi_list();
  605.       return 0;
  606.     }
  607.       break;
  608.  
  609.     case 1:
  610.       for (i=0; i<tracks; i++)
  611.     if (read_track(0))
  612.       {
  613.         free_midi_list();
  614.         return 0;
  615.       }
  616.       break;
  617.  
  618.     case 2: /* We simply play the tracks sequentially */
  619.       for (i=0; i<tracks; i++)
  620.     if (read_track(1))
  621.       {
  622.         free_midi_list();
  623.         return 0;
  624.       }
  625.       break;
  626.     }
  627.   return groom_list(divisions, count, sp);
  628. }
  629.